<template>
  <div class="my-process-container">
    <div class="page-header">
      <h2>我发起的流程</h2>
      <p>查看您发起的流程实例</p>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="流程名称" prop="processName">
            <el-input
              v-model="queryParams.processName"
              placeholder="请输入流程名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="流程状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="进行中" value="RUNNING" />
              <el-option label="已完成" value="COMPLETED" />
              <el-option label="已暂停" value="SUSPENDED" />
              <el-option label="已终止" value="TERMINATED" />
            </el-select>
          </el-form-item>

          <el-form-item label="发起时间" prop="startTime">
            <el-date-picker
              v-model="queryParams.startTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <Icon icon="ant-design:search-outlined" />
              查询
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ant-design:reload-outlined" />
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 流程列表 -->
    <div class="process-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>流程实例列表</span>
            <div class="header-actions">
              <el-button type="primary" @click="startNewProcess">
                <Icon icon="ant-design:plus-outlined" />
                发起流程
              </el-button>
              <el-button @click="refreshList">
                <Icon icon="ant-design:reload-outlined" />
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="processList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />

          <el-table-column prop="processName" label="流程名称" min-width="150">
            <template #default="scope">
              <div class="process-name-cell">
                <Icon icon="ant-design:deployment-unit-outlined" class="process-icon" />
                <span>{{ scope.row.processName }}</span>
                <el-tag
                  v-if="scope.row.processInstanceId === 'PI_001' || scope.row.processInstanceId === 'PI_002'"
                  type="info"
                  size="small"
                  style="margin-left: 8px;"
                >
                  模拟数据
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="businessKey" label="业务Key" min-width="120" />

          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="发起时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="endTime" label="结束时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.endTime) || '-' }}
            </template>
          </el-table-column>

          <el-table-column prop="duration" label="持续时间" width="120">
            <template #default="scope">
              {{ formatDuration(scope.row.duration) }}
            </template>
          </el-table-column>

          <el-table-column prop="currentTask" label="当前节点" min-width="120">
            <template #default="scope">
              <span v-if="scope.row.currentTask">{{ scope.row.currentTask }}</span>
              <span v-else class="no-task">-</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(scope.row)"
              >
                详情
              </el-button>
              <el-button
                v-if="scope.row.status === 'RUNNING' && scope.row.processInstanceId !== 'PI_001' && scope.row.processInstanceId !== 'PI_002'"
                type="warning"
                size="small"
                @click="handleCancelProcess(scope.row)"
              >
                撤销
              </el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button size="small">
                  更多<Icon icon="ant-design:down-outlined" />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="history">审批记录</el-dropdown-item>
                    <el-dropdown-item command="diagram">流程图</el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.status === 'RUNNING'"
                      command="suspend"
                    >
                      暂停
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.status === 'SUSPENDED'"
                      command="resume"
                    >
                      恢复
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="queryParams.page"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 流程详情弹窗 -->
    <ProcessDetailModal
      v-model:visible="detailModalVisible"
      :process-data="selectedProcess"
      mode="view"
      @form-action="handleFormAction"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Icon from '@/components/Icon/Icon.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProcessInstanceList, cancelProcessInstance } from '@/api/workflow/process.api'
import ProcessDetailModal from '@/components/Workflow/ProcessDetailModal.vue'

// 引入统一的夜间模式样式
import '@/components/Workflow/styles/dark-theme.css'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  processName: '',
  status: '',
  startTime: []
})

// 数据
const loading = ref(false)
const processList = ref([])
const total = ref(0)
const selectedRows = ref([])

// 弹窗控制
const detailModalVisible = ref(false)
const selectedProcess = ref(null)

// 查询表单引用
const queryFormRef = ref()

// 加载流程列表
const loadProcessList = async () => {
  loading.value = true
  try {
    console.log('开始加载流程列表，查询参数:', JSON.stringify(queryParams, null, 2))
    const response = await getProcessInstanceList(queryParams)
    console.log('流程列表API响应:', JSON.stringify(response, null, 2))
    console.log('response类型:', typeof response)
    console.log('response是否为对象:', typeof response === 'object')
    console.log('response.data是否存在:', response && response.data)
    console.log('response.data内容:', response?.data)

    // 简化逻辑，直接处理response
    if (response && response.items) {
      // 如果response直接包含items，说明已经是转换后的数据
      processList.value = response.items || []
      total.value = response.total || 0
      console.log('直接使用response数据，数量:', processList.value.length)
    } else if (response && response.data && response.data.items) {
      // 如果response包含data.items，说明是原始响应格式
      processList.value = response.data.items || []
      total.value = response.data.total || 0
      console.log('使用response.data数据，数量:', processList.value.length)
    } else {
      console.log('数据格式不符合预期，显示模拟数据')
      ElMessage.info('暂无流程实例数据，显示模拟数据供参考')
      // 使用模拟数据
      processList.value = [
        {
          id: 1,
          processName: '请假申请流程',
          processKey: 'leave_process',
          processInstanceId: 'PI_001',
          businessKey: 'BUSINESS_001',
          initiator: 'admin',
          status: 'RUNNING',
          startTime: new Date().toISOString(),
          endTime: null,
          duration: null
        },
        {
          id: 2,
          processName: '报销申请流程',
          processKey: 'expense_process',
          processInstanceId: 'PI_002',
          businessKey: 'BUSINESS_002',
          initiator: 'admin',
          status: 'COMPLETED',
          startTime: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
          endTime: new Date().toISOString(),
          duration: 86400000
        }
      ]
      total.value = processList.value.length
    }

    console.log('最终流程列表数据:', processList.value)
    console.log('最终总数:', total.value)

  } catch (error) {
    console.error('加载流程列表失败:', error)
    ElMessage.warning('加载流程列表失败，显示模拟数据供参考。请检查网络连接或联系管理员。')
    // 使用模拟数据
    processList.value = [
      {
        id: 1,
        processName: '请假申请流程',
        processKey: 'leave_process',
        processInstanceId: 'PI_001',
        businessKey: 'BUSINESS_001',
        initiator: 'admin',
        status: 'RUNNING',
        startTime: new Date().toISOString(),
        endTime: null,
        duration: null
      },
      {
        id: 2,
        processName: '报销申请流程',
        processKey: 'expense_process',
        processInstanceId: 'PI_002',
        businessKey: 'BUSINESS_002',
        initiator: 'admin',
        status: 'COMPLETED',
        startTime: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
        endTime: new Date().toISOString(),
        duration: 86400000
      }
    ]
    total.value = processList.value.length
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  loadProcessList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.page = 1
  loadProcessList()
}

// 刷新列表
const refreshList = () => {
  loadProcessList()
}

// 发起新流程
const startNewProcess = () => {
  router.push('/workflow/start')
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  loadProcessList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  loadProcessList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'RUNNING': 'primary',
    'COMPLETED': 'success',
    'SUSPENDED': 'warning',
    'TERMINATED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'RUNNING': '进行中',
    'COMPLETED': '已完成',
    'SUSPENDED': '已暂停',
    'TERMINATED': '已终止'
  }
  return textMap[status] || status
}

// 格式化日期时间
const formatDateTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 格式化持续时间
const formatDuration = (duration) => {
  if (!duration) return '-'
  const hours = Math.floor(duration / 3600000)
  const minutes = Math.floor((duration % 3600000) / 60000)
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}

// 查看详情
const handleViewDetail = (process) => {
  selectedProcess.value = process
  detailModalVisible.value = true
}

// 处理表单操作
const handleFormAction = (action, data) => {
  switch (action) {
    case 'preview':
      ElMessage.info('表单预览功能开发中')
      break
    case 'edit':
      ElMessage.info('表单编辑功能开发中')
      break
    case 'bind':
      ElMessage.info('表单绑定功能开发中')
      break
  }
}

// 撤销流程
const handleCancelProcess = async (process) => {
  try {
    // 检查是否是模拟数据
    if (process.processInstanceId === 'PI_001' || process.processInstanceId === 'PI_002') {
      ElMessage.warning('当前使用的是模拟数据，无法执行撤销操作。请先发起真实的流程实例。')
      return
    }

    await ElMessageBox.confirm(
      `确定要撤销流程"${process.processName}"吗？撤销后流程将终止。`,
      '确认撤销',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await cancelProcessInstance(process.processInstanceId, '用户主动撤销')
    ElMessage.success('流程撤销成功')
    loadProcessList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤销流程失败:', error)
      ElMessage.error('撤销流程失败')
    }
  }
}

// 处理下拉菜单命令
const handleCommand = (command, process) => {
  selectedProcess.value = process

  switch (command) {
    case 'history':
      // 审批历史已集成到流程详情组件中
      detailModalVisible.value = true
      break
    case 'diagram':
      // 流程图已集成到流程详情组件中
      detailModalVisible.value = true
      break
    case 'suspend':
      handleSuspendProcess(process)
      break
    case 'resume':
      handleResumeProcess(process)
      break
  }
}

// 暂停流程
const handleSuspendProcess = async (process) => {
  try {
    await ElMessageBox.confirm('确定要暂停此流程吗？', '确认暂停', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // TODO: 调用暂停流程API
    ElMessage.success('流程暂停成功')
    loadProcessList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('暂停流程失败:', error)
      ElMessage.error('暂停流程失败')
    }
  }
}

// 恢复流程
const handleResumeProcess = async (process) => {
  try {
    await ElMessageBox.confirm('确定要恢复此流程吗？', '确认恢复', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // TODO: 调用恢复流程API
    ElMessage.success('流程恢复成功')
    loadProcessList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复流程失败:', error)
      ElMessage.error('恢复流程失败')
    }
  }
}

onMounted(() => {
  loadProcessList()
})
</script>

<style scoped>
.my-process-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.filter-section {
  margin-bottom: 24px;
}

.process-section {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.process-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.process-icon {
  color: #409eff;
}

.no-task {
  color: #999;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
